package modules

import (
	"context"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
	"missevanbot/config"
	"missevanbot/models"
	"missevanbot/utils"
)

const (
	Prefix          = "missevan:"
	PrefixCookies   = Prefix + "cookies:"
	PrefixWords     = Prefix + "words:"
	PrefixTemplates = Prefix + "templates:"
	PrefixAlive     = Prefix + "alive:"
	PrefixOnline    = Prefix + "online:"
	PrefixGlobal    = Prefix + "global:"
	PrefixInvisible = PrefixGlobal + "invisible:"

	KeySupervisor = Prefix + "supervisor"
	KeyExtendChar = Prefix + "char"
	KeyLuckWords  = Prefix + "luckwords"
	KeyWordWater  = PrefixWords + "water"
)

const (
	BoardCommon  = "common"
	BoardSinging = "singing"
	BoardPander  = "pander"
	BoardLove    = "love"
)

var (
	rdb  *redis.Client
	push config.PushConfig
	ctx  = context.Background()
)

func Init() {
	rdb = config.RDB
	push = config.Push()
}

// prefixRoom returns the string `missevan:[RoomID]:`
func prefixRoom(rid int64) string {
	return Prefix + utils.Itoa(rid) + ":"
}

// NewFeedback pushes a feat string to the features list.
func NewFeedback(room *models.Room, user models.FmUser, fb string) {
	text := fmt.Sprintf("(Time:%s|RID:%d|Alias:%s|UID:%d|Username:%s) %s",
		time.Now().Format("2006-01-02T15:04:05"),
		room.ID, room.Alias, user.UserID, user.Username, fb)
	rdb.RPush(ctx, Prefix+"feedback", text)
}

// Welcome fetches the global welcome message.
func Welcome(uid int64) string {
	key := Prefix + "welcome"
	return rdb.HGet(ctx, key, utils.Itoa(uid)).Val()
}

// SetNickname stores the nic to Redis server.
// The key of the nickname is specified by UID.
func SetNickname(uid int64, nic string) {
	rdb.HSet(ctx, Prefix+"nickname", utils.Itoa(uid), nic)
}

// Nickname returns the nickname that queried by UID.
func Nickname(uid int64) string {
	return rdb.HGet(ctx, Prefix+"nickname", utils.Itoa(uid)).Val()
}

func TextBoard(board string) string {
	key := Prefix + "boards:" + board // missevan:boards:[board]
	if rdb.Exists(ctx, key).Val() != 1 {
		// Key not exists, use the default text board.
		key = Prefix + "boards:" + BoardCommon
	}
	return rdb.SRandMember(ctx, key).Val()
}

func ExtendChar(c string) string {
	return rdb.HGet(ctx, KeyExtendChar, c).Val()
}
